import { Component, Input, Output, EventEmitter, OnInit, OnChanges } from '@angular/core';
import { NzNotificationService } from 'ng-zorro-antd';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { HttpServcie } from '../../../service/http.service';
import { Config } from '../../../service/config';
import { el } from "@angular/platform-browser/testing/src/browser_util";
import { FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms';
import { OnelevatorInfo } from './bean/onelevator.bean';
import { FileUploader, FileItem, ParsedResponseHeaders } from 'ng2-file-upload';
import { Observable } from 'rxjs/Rx';
import { NzModalService, NzModalSubject } from 'ng-zorro-antd';
@Component({
    selector: 'onelevator-info',
    templateUrl: 'onelevator-info.html',
    styleUrls: ['onelevator-info.scss']
})
/**
 *一梯一档修改
 */
export class OnelevatorInfoPage implements OnInit, OnChanges {
    validateForm: FormGroup;
    isSpinning: boolean = false;
    functions: any = [];
    currentModal: NzModalSubject;
    expandDataCache = {};
    @Input() inValue: any = [];
    data = [];
    @Output("outPut") outPut = new EventEmitter();
    config: any = Config;
    showImage: any = [];
    // private config:any=Config;
    //一梯一档信息
    //接收参数
    oneLevatorBean: OnelevatorInfo = new OnelevatorInfo();
    //电梯添加的权限
    funList: any = [];
    //机构的集合
    partyList: any = [];
    partyId: string;
    isVisible = false;
    isConfirmLoading = false;

    fileUploader = new FileUploader({
        url: Config.IP + Config.API.upload,
        method: "POST",
        itemAlias: "file",
        autoUpload: false,
        headers: [
            { name: "Authorization", value: 'Bearer ' + window.localStorage['token'] }
        ]
    });
    constructor(
        private fb: FormBuilder,
        private httpServcie: HttpServcie,
        private _notification: NzNotificationService,
        private route: ActivatedRoute,
        private nsub: NzModalSubject,
        private modalService: NzModalService
    ) {

    }
    /**
     * 选择checkbox
     * @param event
     * @param param
     */
    refreshStatus(event, param) {
        if (event) {
            this.funList.push(param);
        } else {
            //如果非选中状态移除
            if (this.funList.length > 0) {
                this.httpServcie.removeByValue(this.funList, param);
            }
        }
    }

    ngOnInit() {
        this.validateForm = this.fb.group({

            projectName: [null, [Validators.required]],
            contractNum: [null, [Validators.required]],
            usedOrgName: [null, [Validators.required]],
            usedOrgAddress: [null, [Validators.required]],
            elevatorOrgAddress: [null, [Validators.required]],
            registerId: [null, [Validators.required]],
            registrationCard: [null, [Validators.required]],
            cantacts: [null, [Validators.required]],
            phoneNUm: [null, [Validators.required]],
            fax: [null, [Validators.required]],
            conformityCertificate: [null, [Validators.nullValidator]],
            salesInstallationContract: [null, [Validators.nullValidator]],
            installationNotification: [null, [Validators.nullValidator]],
            inspectionRequisition: [null, [Validators.nullValidator]],
            selfCheckRecord: [null, [Validators.nullValidator]],
            supervisionApply: [null, [Validators.nullValidator]],
            acceptanceReport: [null, [Validators.nullValidator]],
            completionDocuments: [null, [Validators.nullValidator]],
            installationAcceptanceRecord: [null, [Validators.nullValidator]],
            siteProblemReport: [null, [Validators.nullValidator]],
            constructionDesignScheme: [null, [Validators.nullValidator]],
            safetyTechnicalDisclosure: [null, [Validators.nullValidator]],
            unpackingRecord: [null, [Validators.nullValidator]],
            safetyComponentsTestReport: [null, [Validators.nullValidator]],
            annualInspectionReport: [null, [Validators.nullValidator]],
            routineMaintenance: [null, [Validators.nullValidator]],
            elevatorMaintenanceContract: [null, [Validators.nullValidator]],
            remarks: [null, [Validators.nullValidator]],
            personShouze: [null, [Validators.nullValidator]],
            personRcglRyzz: [null, [Validators.nullValidator]],
            jsrczgz: [null, [Validators.nullValidator]],
            jcwhczgz: [null, [Validators.nullValidator]],
            cgjczd: [null, [Validators.nullValidator]],
            whbyzd: [null, [Validators.nullValidator]],
            dqbjzd: [null, [Validators.nullValidator]],
            pxkhzd: [null, [Validators.nullValidator]],
            ywyjyxzd: [null, [Validators.nullValidator]],
            dtaqglzd: [null, [Validators.nullValidator]],
            ysglzd: [null, [Validators.nullValidator]],
            sbfbt: [null, [Validators.nullValidator]],
            dtztz: [null, [Validators.nullValidator]],
            wbjhb: [null, [Validators.nullValidator]],
            zyryda: [null, [Validators.nullValidator]],
            wbryda: [null, [Validators.nullValidator]],
            dxgzjdbj: [null, [Validators.nullValidator]],
            ndqjybj: [null, [Validators.nullValidator]],
        });

        this.route.paramMap.subscribe(data => {
            //查询电梯的信息
            this.oneLevatorBean.usedPartyId = JSON.parse(window.localStorage['user']).partyId;
            this.httpServcie.getElevatorAppraisByid(this.oneLevatorBean.usedPartyId).subscribe(datas => {
                if (datas.data) {
                    this.oneLevatorBean = datas.data;
                }

            })
        });

    }
    ngOnChanges() {

    }
    submitForm($event, data) {
        //校验是否能提交
        //没有填的标红
        for (const i in this.validateForm.controls) {
            this.validateForm.controls[i].markAsDirty();
        }
        //处理是否提交
        for (const i in this.validateForm.controls) {
            if (!this.validateForm.controls[i].valid) {
                return;
            }
        }
        // if(this.showImage!=null){
        //     let urls:string="";
        //     this.showImage.forEach(element=>{
        //         urls+=element+",";
        //     })
        //     this.oneLevatorBean.qualificationsUrl=urls.substring(0,urls.length-1);
        // }
        this.isSpinning = true;
        let ob = this.httpServcie.elevatorAppraisAdd(this.oneLevatorBean);
        ob.subscribe((data) => {
            this.isSpinning = false;
            if (data.status == 200) {
                this._notification.create('success', '成功提示', '修改成功');
                this.outPut.emit($event);
            } else {
                this._notification.create('error', '失败提示', data.message);
                return;
            }
        })

    }
    //交验
    getFormControl(name) {
        return this.validateForm.controls[name];
    }
    //选择文件后调用的方法
    selectedFileOnChanged(event, param) {
        let list: any = [];
        if (this.oneLevatorBean[param]) {
            this.oneLevatorBean[param].split(",").forEach(element => {
                list.push(element);
            });
        }
        if (event.target.files[0].type.match('image.*')) {
            //手动上传的
            this.fileUploader.uploadAll();
            this.fileUploader.onSuccessItem = (item: FileItem, response: string, status: number, headers: ParsedResponseHeaders) => {
                if (status == 200) {
                    //判断是否是图片
                    if (item.file.type.match('image.*')) {
                        let urls: string = "";
                        list.push(JSON.parse(response).data);
                        list.forEach(element => {
                            urls += element + ",";
                        });
                        this.oneLevatorBean[param] = urls.substring(0, urls.length - 1);
                    } else {
                        this._notification.create('warning', '警告提示', '请选择图片类型！');
                    }
                }
            }
        } else {
            this.fileUploader.clearQueue();
            this._notification.create('warning', '警告提示', '请选择图片类型！');
        }
    }

    getParamList(param) {
        let list: any = [];
        if (!this.oneLevatorBean[param]) {
            return list;
        } else {
            this.oneLevatorBean[param].split(",").forEach(element => {
                list.push(element);
            });
            return list;
        }
    }
    delete(param, ziduan) {
        this.httpServcie.deleteUpload(param).subscribe(data => {
            if (data.status == 200) {
                let list = this.oneLevatorBean[ziduan].split(",");
                this.httpServcie.removeByValue(list, param);
                this.oneLevatorBean[ziduan] = list.join(',');
                //this._notification.create('success', '成功提示', '移除成功');
            } else {
                //this._notification.create('error', '失败提示', data.message);
                return;
            }
        }, error => {

        });
    }

    handleOk = (e) => {
        this.oneLevatorBean.usedPartyId = this.partyId;
        let ob = this.httpServcie.elevatorAppraisUpdate(this.oneLevatorBean);
        ob.subscribe((data) => {
            this.isSpinning = false;
            if (data.status == 200) {
                this._notification.create('success', '成功提示', '修改成功');
                this.isVisible = false;
            } else {
                this._notification.create('error', '失败提示', data.message);
            }
            this.ngOnInit();
        })
    }

    handleCancel = (e) => {
        this.isVisible = false;
    }

    showModal = () => {
        this.isVisible = true;
        let parentId = JSON.parse(window.localStorage.getItem("user")).partyParentId;
        this.httpServcie.queryByIdAndTypeList({ partyType: 2 }).subscribe(data => {
            this.partyList = data.data;
        });
    }
}
